import logging
import logging.handlers
import os
import sys
import colorlog

logger = logging.getLogger()


def setLogger(config):
    name = config.get('log', 'fileName')  # 是否开启日志
    enable = config.get('log', 'enable')  # 是否开启日志
    console = config.get('log', 'console')  # 是否输出到控制台
    journal = config.get('log', 'journal')  # 是否输出到文件
    logPath = config.get('log', 'logPath')  # 日志文件路径
    level = config.get('log', 'level')  # 日志级别
    when = config.get('log', 'when')  # 日志文件时间间隔
    backupCount = config.get('log', 'backupCount')  # 日志文件周期

    log_colors_config = {
        'DEBUG': 'white',  # cyan white
        'INFO': 'green',
        'WARNING': 'yellow',
        'ERROR': 'red',
        'CRITICAL': 'bold_red',
    }

    if not logPath:
        logPath = os.path.join(os.getcwd(), 'logFile')
    else:
        logPath = os.path.join(logPath, 'logFile')


    # print(logPath)
    os.makedirs(logPath, 0o755, True)

    sh_fmt = colorlog.ColoredFormatter(
        fmt='%(log_color)s[%(asctime)s.%(msecs)03d] %(filename)s:%(lineno)d [%(levelname)s]: %(message)s',
        datefmt='%Y-%m-%d  %H:%M:%S',
        log_colors=log_colors_config)
    sh_fmt_file = logging.Formatter("[%(asctime)s] %(filename)s:%(lineno)d [%(levelname)s]: %(message)s")
    logger.setLevel(level)

    if enable:
        # 输出到控制台
        if console:
            sh = logging.StreamHandler(sys.stdout)
            sh.setLevel(level)
            sh.setFormatter(fmt=sh_fmt)
            logger.addHandler(sh)

        # 输出到文件
        if journal:
            th = logging.handlers.TimedRotatingFileHandler(
                filename=os.path.join(logPath, name),
                when=when,
                backupCount=backupCount,
                encoding='utf-8',
            )
            th.setFormatter(sh_fmt_file)
            logger.addHandler(th)


if __name__ == '__main__':
    print('aaa'.startswith('1'))
